﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace HgRemoteServer
{
	public class CmdRunner
	{
		Process p;

		public string LastMessage { get; private set; }
		public bool Exited { get; private set; }

		public CmdRunner(string cmd, string arguments, string wd)
		{
			ProcessStartInfo psi = new ProcessStartInfo(cmd, arguments);
			psi.WorkingDirectory = wd;
			psi.UseShellExecute = false;
			psi.CreateNoWindow = true;

			p = new Process();
			p.StartInfo = psi;
			p.EnableRaisingEvents = true;
			p.Exited += new EventHandler(OnExit);

			psi.RedirectStandardError = true;
			psi.RedirectStandardOutput = true;
		}

		void OnSetLastMessage(object sender, DataReceivedEventArgs e)
		{
			LastMessage = e.Data;
		}

		void OnAddToOutput(object sender, DataReceivedEventArgs e)
		{
			lines.Add(e.Data);
		}

		public void Start()
		{
			p.OutputDataReceived += new DataReceivedEventHandler(OnSetLastMessage);
			p.ErrorDataReceived += new DataReceivedEventHandler(OnSetLastMessage);
			p.Start();
			p.BeginErrorReadLine();
			p.BeginOutputReadLine();
		}

		public int WaitForExit()
		{
			p.WaitForExit();
			return p.ExitCode;
		}

		private List<string> lines;
		public List<string> GetOutputLines()
		{
			lines = new List<string>(100);
			p.OutputDataReceived += new DataReceivedEventHandler(OnAddToOutput);
			p.ErrorDataReceived += new DataReceivedEventHandler(OnAddToOutput);
			p.Start();
			p.BeginErrorReadLine();
			p.BeginOutputReadLine();
			p.WaitForExit();
			return lines;
		}

		public void Abort()
		{
			if (!p.HasExited)
				p.Kill();
		}

		void OnExit(object sender, EventArgs e)
		{
			Exited = true;
		}
	}
}
